//
//  TradeOrderViewModel.swift
//  Exchange
//
//  Created by rui on 2018/4/25.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class TradeOrderListViewModel: BaseViewModel {
    
    var isNoMoreData = false
    
    var status: Int8 = 0 ///0 进行中 1 已完成
    var page: Int = 1
    let size: Int = 15
    
    var dataArray = [TradeOrderListModel]()
    
    private lazy var tradeoOrderApi: TradeOrderListRequest = {
        let api = TradeOrderListRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
  
    
    func loadNewData() {
        self.page = 1
        self.tradeoOrderApi.loadData()
    }
    
    func loadMoreData() {
        self.page += 1
        self.tradeoOrderApi.loadData()
    }
    
}

extension TradeOrderListViewModel: RequestCallBack,RequestDataReformer,RequestParamSource {
    
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        if let _ = request as? TradeOrderListRequest {
            var flag = false
            if let realyData = data?["data"] as? [String:Any] {
                if let list = realyData["list"] as? [[String:Any]] {
                    if let jsonData = list.jsonData {
                        do{
                            let list = try JSONDecoder().decode(Array<TradeOrderListModel>.self, from: jsonData)
                            if self.page == 1 {
                                self.dataArray.removeAll()
                            }
                            if let hasNext =  realyData["hasNextPage"] as? Bool {
                                self.isNoMoreData = !hasNext
                            }
                            self.dataArray.append(contentsOf: list)
                            flag = true
                        }catch {
                            flag = false
                            dPrint(error)
                        }
                    }
                }
            }
            if !flag {
                self.page -= 1
            }
            self.response?(ResponseState.trade_order_list,flag, nil)
        }
    }
    
    func requestDidSucess(_ request: BaseRequest) {
        self.isNoMoreData = false
    }
    
    func requestDidFail(_ request: BaseRequest) {
        self.isNoMoreData = false
        if let _ = request as? TradeOrderListRequest {
            self.page -= 1
            self.response?(ResponseState.trade_order_list,false, request.errorMsg)
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        var pramas: [String:Any] = [:]
        if let _ = request as? TradeOrderListRequest {
            pramas.updateValue(size, forKey: "size")
            pramas.updateValue(page, forKey: "page")
            pramas.updateValue(status, forKey: "status")
        }
        return pramas
    }
    
}
